<?php

namespace App\Services\SpiderContent;

use Carbon\Carbon;
use App\Models\User;
use App\Models\News;
use App\Jobs\RewardFirstParentJob;
use Illuminate\Support\Facades\Log;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Database\Eloquent\Collection;
use Sunra\PhpSimple\HtmlDomParser;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use JonnyW\PhantomJs\Client;

use DOMDocument;


class SpiderKeContent
{

    public function execute($baseUrl)
    {
    	ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');

    	
    	//$url = "https://www.baidu.com";
    //	$html = file_get_contents($baseUrl);
    	$headers[] = "Content-type: application/x-www-form-urlencoded";

    	$curl = curl_init(); // 启动一个CURL会话

		curl_setopt($curl, CURLOPT_URL, $baseUrl);

		curl_setopt($curl, CURLOPT_HEADER, 0);

		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查

		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在


       // curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // 关键在这里
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		 
		// 执行cURL会话
		$html = curl_exec($curl);

		//$content = mb_convert_encoding($html, 'UTF-8', 'ISO-8859-1');
		//dd($content);
    	//$html = '<a href="aaaa"><div class="content-item"><div>测试</div></div></a>';
    	$dom = new DOMDocument();
    	

    	libxml_use_internal_errors(true);
    	//$html = htmlspecialchars($html);
    	
		
        $dom->loadHTML('<?xml encoding="UTF-8">' . $html);
      
        $elements = $dom->getElementsByTagName('div');

     	//$html = HtmlDomParser::str_get_html($html);

     	//dd($elements->nodeValue);

     	$data = [];
     	$i = 0;

     	$MinutsMatch = "/\d+小时前/";
        foreach($elements as $key=>$val){
        	$url = "";

    		if (strpos($val->getAttribute('class'), 'information-flow-item') !== false) {
    			
    	 		$content = $dom->saveHTML($val);
    	 		
    	 		if(strstr($content,'小时前')){
    	 			$matchTime = 0;
    	 			preg_match($MinutsMatch,$content,$match);
    	 			if(!empty($match)){
    	 				preg_match('/\d+/',$match[0],$times);
    	 				$matchTime = $times[0];
    	 			}

    	 			$data[$i]= ["images"=>"","brief"=>'',"content_cn"=>"","title_cn"=>"","images"=>"",'source'=>'36ke',"created_at"=>Carbon::now(),"url"=>"","started_at"=>Carbon::now()->subMinutes($matchTime)];
    	 			

	    	 		$childNode = $val->childNodes[1]->childNodes[0]->childNodes[1];

	    	 		
	    	 		$attrs= $childNode->childNodes[0]->childNodes[0]->attributes;
	    	 		//dd($dom->saveHTML($childNode->childNodes[0]->childNodes[0]));
	    	 		$url = "";
	    	 		foreach($attrs as $attr){
	    	 			if($attr->nodeName =="href"){

    	 					$data[$i]['url'] = "https://36kr.com".$attr->textContent;
    	 					
    	 				}
	    	 			
	    	 		}

	    	 		//$imgNode = $childNode->childNodes[0]->childNodes[0]->childNodes[0];
	    	 		/*dd($dom->saveHTML($childNode->childNodes[0]->childNodes[0]));
	    	 		$data[$i]['title_cn'] = $imgNode->attributes[1]->textContent;
	    	 		$img=  $imgNode->attributes[0]->textContent;
	    	 		if($img){

    					$imageContent = file_get_contents($img);

						$newFileName = "/images/".Str::random(40) . '.jpg'; // 假设是JPG格式
						Storage::disk('oss')->put($newFileName, $imageContent);
						
						// 你现在可以通过存储的路径访问图片
						$data[$i]['images'] = Storage::disk('oss')->path($newFileName);
						
    				}*/
    				dd($data[$i]['url']);
    				$contentHtml = file_get_contents($data[$i]['url']);
	        	dd($contentHtml);
		        	$contentDom = new DOMDocument();

		        	$contentDom->loadHTML('<?xml encoding="UTF-8">' . $contentHtml);
		        	$Contentelements = $contentDom->getElementsByTagName('div');

		        	 foreach($Contentelements as $contentKey=>$contentVal){

			        	if (strpos($contentVal->getAttribute('class'), 'articleDetailContent') !== false) {
	        			
	        				$data[$i]['content_cn'] = $contentVal->textContent;
	        				dd($data);

	        				$i++;

	        			}
	        		}
	        		
    	 		}	
	        		
    		 }

        	
        	  
		}


		DB::table('deep_news')->insert($data);
		//dd($data);
     	 
    	//dd($elements);

     	//dd(retrieve_url_contents($url));
     	//$html = file_get_contents('https://www.huxiu.com/club/1000.html?object_type=51&object_id=1');
     	//dd($html);
 
		
    }


    public function djNodes($nodes,$res)
    {
    	if($nodes->nextSibling && $nodes->nextSibling->nodeName!="h4"){

    		$res['content'] = $res['content'].$nodes->nextSibling->textContent;


    		if($nodes->nextSibling->childNodes){

    			foreach($nodes->nextSibling->childNodes as $nn){
    				if($nn->nodeName=="img"){
    					$res['image'] = $nn->getAttribute('src');
    				}
    			}
    		}
    		
    		if(isset($nodes->nextSibling->nextSibling)  && $nodes->nextSibling->nextSibling->nodeName != "h4"){

    			 $res = $this->djNodes($nodes->nextSibling,$res);
    		}
    	}

    	return  $res;
    	//dd($nodes->nextSibling->nextSibling);
    	

    }

	function getUrlSize($url) {
	    // 初始化cURL

	   ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727;)');

	    $ch = curl_init($url);
	     dd($ch);
	    // 设置cURL选项
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_HEADER, 1);
	    curl_setopt($ch, CURLOPT_NOBODY, 1);
	    
	    // 执行cURL请求
	    $output = curl_exec($ch);
	    // 获取内容长度
	    $size = 0;
	    if (preg_match('/Content-Length: (\d+)/', $output, $matches)) {

	        $size = (int)$matches[1];
	    }
	    
	    // 关闭cURL
	    curl_close($ch);
	    
	    return $size;
	}

	public function __invoke()
	{
		
		$baseUrl1 = "https://36kr.com/information/technology/";
		//Dinglog::text("========== refresh seckill product num start ......");

		//$today = date("Y-m-d");

		$client = Client::getInstance();
		 $request  = $client->getMessageFactory()->createRequest();
	     $response = $client->getMessageFactory()->createResponse();

	     $request->setMethod('GET');
	     $request->setUrl($baseUrl1);

		  // Send the request
		  $client->send($request, $response);

		  if($response->getStatus() === 200) {

		      // Dump the requested page content
		      dd( $response->getContent());
		  }

		  dd(123);
		

		$this->execute($baseUrl1);

		//Dinglog::text("========== refresh seckill product num end ......");
	}
}
